package control;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserData;

/**
 * Servlet implementation class Recharge
 */
public class Recharge extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Recharge() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String user = request.getParameter("email");
		String idcard = request.getParameter("idcard");
		String idSericard = request.getParameter("idSericard");
		String user_err = "";
		String idcard_err = "";
		UserData us = new UserData();
		boolean checkidcard = us.checkIdcard(idcard, idSericard);
		boolean checkuser = us.checkUserName(user);
		if (user.equals("")) {
			user_err = " bạn chưa nhập tài khoản !";
		}else if(!checkuser){
			user_err = " Tài Khoản Không đúng !";
		}
		if (idcard.equals("") || idSericard.equals("")) {
			idcard_err = " Bạn chưa nhập số seri Hoặc mã thẻ  !";
		}else if(!checkidcard){
			idcard_err = "Mã thẻ , Số Seri không đúng hay đã sử dụng";
		}
		if(checkidcard && checkuser){
			long time =System.currentTimeMillis();
			String date = Calendar.getInstance().getTime().toString();
			double amount = UserData.getAmountCard(idSericard);
			UserData.updateMoney(user, amount);
			UserData.EnableCard(idSericard);
			UserData.addCardUser(idSericard, time, date, user);
			
			
		}
		String url = "/index.jsp";
		if (user_err.length() > 0 ||idcard_err.length() > 0) {
			url = "/napthe.jsp";
			request.setAttribute("user_err", user_err);
			request.setAttribute("idcard_err", idcard_err);
		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
		rd.forward(request, response);
	}

}
